<?php

namespace Lims\PaymentBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Utils\SecurityBundle\CustomClass\SecurityFunctions;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Lims\MainBundle\Entity\Payment;
use Lims\MainBundle\Entity\PaymentScheduleMap;
use Lims\PaymentBundle\Exception\PaymentException;
use Lims\MainBundle\Entity\CreditSchedule;


class PaymentController extends Controller
{
    public function listAction()
    {
        return $this->render('LimsPaymentBundle:Payment:list.html.twig', array());
    }
    
    public function addAction($contractId = null)
    {
        return $this->render('LimsPaymentBundle:Payment:add.html.twig', array('contractId' => $contractId));
    }
    
    public function contractNumberAction()
    {
        $em = $this->get('doctrine')->getManager();
        
        // get contract number
        if(!isset($_POST['contractNumber']))
        {
            $response = new Response(json_encode(array('status' => 'failed', 'msg' => 'Гэрээний дугаар оруулана уу!')));
            $response->headers->set('Content-Type', 'application/json');
            return $response;
        
            
        }
        // check contract number
        $contractNumber = SecurityFunctions::clear($_POST['contractNumber']);
        if(strlen($contractNumber) == 0)
        {
            $response = new Response(json_encode(array('status' => 'failed', 'msg' => 'Гэрээний дугаар оруулана уу!')));
            $response->headers->set('Content-Type', 'application/json');
            return $response;
        }
        
        // find
        $paymentSchedule = $em->getRepository('LimsMainBundle:CreditSchedule')->findPaymentSchedule($contractNumber);
        if(!$paymentSchedule)
        {
            $result = array('status' => 'failed', 'data' => null);
        }else{
            $paymentSchedule['graph'] = $this->getGraph();
            $creditInformationForPayment = $em->getRepository('LimsMainBundle:Credit')->findCreditInformationForPayment($contractNumber);

            $paymentSchedule['CREDIT'] = $creditInformationForPayment;

            $result = array('status' => 'success', 'data' => $paymentSchedule);
        }
        
        $response = new Response(json_encode($result));
        $response->headers->set('Content-Type', 'application/json');
        return $response;
    }
    
    public function savePaymentAction()
    {
        $em = $this->get('doctrine')->getManager();
        $userId = $this->container->get('security.context')->getToken()->getUser()->getId();
        
        // get paramters
        $paymentParams = $this->checkPaymentParams();
        
        // save
        try{
            
            // loop
            foreach($paymentParams['PAYMENTS'] AS $k => $paidAmount)
            {
                // save Payment
                $payment = new Payment();
                $payment->setPaymentMethodId(null);
                $payment->setPaidAmount($paidAmount);
                $payment->setTargetDate(new \DateTime($paymentParams['TARGET_DATES'][$k]));
                $payment->setTargetUser($em->getRepository('LimsMainBundle:Users')->findOneBy(array('id' => $userId, 'isActive' => 1)));
                $payment->setDocumentNumber(null);
                $payment->setCreatedDate(new \DateTime(date('Y-m-d h:i:s')));
                $payment->setCreatedUser($em->getRepository('LimsMainBundle:Users')->findOneBy(array('id' => $userId, 'isActive' => 1)));
                $payment->setIsActive(1);
                $payment->setCreatedIp('ip');

                $em->persist($payment);
                
                // save PaymentScheduleMap
                $paymentScheduleMap = new PaymentScheduleMap();
                $paymentScheduleMap->setCreditId($paymentParams['CREDIT_ID']);
                
                // set Schedule
                $schedule = $em->getRepository('LimsMainBundle:CreditSchedule')->findOneBy(array('id' => $paymentParams['CREDIT_SCHEUDLE_IDS'][$k], 'isActive' => 1));                
                $this->checkOldSchedule($em, $schedule);
                $paymentScheduleMap->setSchedule($schedule);
                
                $paymentScheduleMap->setPayment($payment);
                $paymentScheduleMap->setIsActive(1);
                $paymentScheduleMap->setCreatedDate(new \DateTime(date('Y-m-d h:i:s')));
                $paymentScheduleMap->setCreatedUser($em->getRepository('LimsMainBundle:Users')->findOneBy(array('id' => $userId, 'isActive' => 1)));
                $paymentScheduleMap->setPaidAmount($paidAmount);                
                $paymentScheduleMap->setBalance($paymentParams['BALANCES'][$k]);
                
                $em->persist($paymentScheduleMap);
                
            }
            
            $em->flush();
            
            $this->get('session')->getFlashBag()->add('notice', ' Төлөлт амжилттэй хийгдэлээ.');
            return new RedirectResponse($this->generateUrl('lims_payment_add', array('contractId' => $paymentParams['CONTRACT_ID'])));
                
        }  catch (PaymentException $e)
        {
            $this->get('session')->getFlashBag()->add('error', $e->message);
            return new RedirectResponse($this->getRequest()->headers->get('referer'));            
        }  catch (\Exception $e)
        {
            var_dump($e);die;
            $this->get('session')->getFlashBag()->add('error', 'Амжилтгүй боллоо');
            return new RedirectResponse($this->getRequest()->headers->get('referer'));
        }
        
        
        
    }
    
    private function checkPaymentParams()
    {
        if(!isset($_POST['payments']) || !isset($_POST['balances']) || !isset($_POST['target_dates']) || !isset($_POST['ids']))
        {
            throw new PaymentException('PAY_1001', 'Төлөлт өдөр, Төлөлт дүн, Үлдэгдэл бүрэн бөглөнө үү.');
        }
        
        if((count($_POST['payments']) != count($_POST['balances'])) && (count($_POST['target_date']) != count($_POST['balances'])) && (count($_POST['target_date']) != count($_POST['ids'])) )
        {
            throw new PaymentException('PAY_1002', 'Төлөлт өдөр, Төлөлт дүн, Үлдэгдэл хоорондоо таарахгүй байна.');
        }
        
        $creditScheduleIds = array();
        foreach($_POST['ids'] AS $creditScheduleId)
        {
            array_push($creditScheduleIds, (int) $creditScheduleId);
        }
        
        $targetDates = array();
        foreach($_POST['target_dates'] AS $targetDate)
        {
            array_push($targetDates, SecurityFunctions::clear($targetDate));
        }
        
        $payments = array();
        foreach($_POST['payments'] AS $payment)
        {
            if($payment == null)
            {
                array_push($payments, null);
            }else{
                array_push($payments, (float) $payment);
            }
            
        }
        
        $balances = array();
        foreach($_POST['balances'] AS $balance)
        {
            if($balance == null)
            {
                array_push($balances, null);
            }else{
                array_push($balances, (float) $balance);
            }
            
        }
        
        return array('CREDIT_SCHEUDLE_IDS' => $creditScheduleIds, 'TARGET_DATES' => $targetDates, 'PAYMENTS' => $payments, 'BALANCES' => $balances, 'CREDIT_ID' => (int) $_POST['creditId'], 'CONTRACT_ID' => (int) $_POST['contractId']);
    }
    
    private function checkOldSchedule($em, CreditSchedule $schedule = null)
    {
        if($schedule == null)
        {
            return false;
        }
        
        $paymentScheduleMaps = $em->getRepository('LimsMainBundle:PaymentScheduleMap')->findBy(array('schedule' => $schedule, 'isActive' => 1));        
        if($paymentScheduleMaps)
        {
            foreach($paymentScheduleMaps AS $paymentScheduleMaps )
            {
                $paymentScheduleMaps->setIsActive(0);
                $em->persist($paymentScheduleMaps);
            }
            
            return true;
        }
        
        return false;
    }
    
    private function getGraph()
    {
        
    }
    
    public function getPaymentAction()
    {
        $em = $this->get('doctrine')->getManager();
        
        // get contract number
        if(!isset($_POST['creditId']))
        {
            $response = new Response(json_encode(array('status' => 'failed', 'msg' => 'Зээлийн график олдсонгүй!')));
            $response->headers->set('Content-Type', 'application/json');
            return $response;
        
            
        }
        // check scheduleId
        $creditId = (int) $_POST['creditId'];
        if($creditId == 0)
        {
            $response = new Response(json_encode(array('status' => 'failed', 'msg' => 'Зээлийн график олдсонгүй!')));
            $response->headers->set('Content-Type', 'application/json');
            return $response;
        }
        
        // find
        $paymentSchedule = $em->getRepository('LimsMainBundle:Payment')->getPaymentForInquiryFull($creditId);        
        if(!$paymentSchedule)
        {
            $result = array('status' => 'failed', 'data' => null);
        }else{
            $result = array('status' => 'success', 'data' => $paymentSchedule);
        }
        
        $response = new Response(json_encode($result));
        $response->headers->set('Content-Type', 'application/json');
        return $response;
    }
    
}
